/*
https://leetcode-cn.com/problems/next-greater-element-ii/solution/xia-yi-ge-geng-da-yuan-su-ii-by-leetcode-bwam/
 */
import java.util.Arrays;
import java.util.Stack;

public class Solution503 {
    public int[] nextGreaterElements(int[] nums) {
        Stack<Integer> stack=new Stack<>();
        int[] ans=new int[nums.length];
        Arrays.fill(ans,Integer.MIN_VALUE);
        for (int i=0;i<2*nums.length;i++){
            while (!stack.isEmpty() && nums[stack.peek()]<nums[i%nums.length]){
                ans[stack.pop()]=nums[i%nums.length];
            }
            stack.push(i%nums.length);
        }
        for (int i=0;i<nums.length;i++){
            if (ans[i]==Integer.MIN_VALUE){
                ans[i]=-1;
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(new Solution503().nextGreaterElements(new int[]{1,2,1})));
    }
}
